#include "def.h"
#include "44b.h"
#include "option.h"
#include "utils.h"

static U16 SerialPortSel;

U16 SerialSwitch(U16 port)
{
#ifdef	SERIAL_PORTS_SWITCH
//	U16 old_sel = SerialPortSel;

	SerialPortSel = port?1:0;
#else
	SerialPortSel = 0;
#endif
	return SerialPortSel;
}

void SerialChgBaud(U32 baud)
{
	U32 mclk =  GetMasterClock();
	
	rUFCON0 = 0x0;		//FIFO disable
	rUFCON1 = 0x0;
	rUMCON0 = 0x0;
	rUMCON1 = 0x0;
//UART0
//	rULCON0  = 0x7;		//Normal,No parity,2 stop,8 bit
	rULCON0  = 0x3;		//Normal,No parity,1 stop,8 bit
	rUCON0   = 0x245;	//rx=edge,tx=level,disable timeout int.,enable rx error int.,normal,interrupt or polling
	rUBRDIV0 = ((int)(mclk/16./baud + 0.5) -1);
//UART1
//	rULCON1  = 0x7;		//Normal,No parity,2 stop,8 bit
	rULCON1  = 0x3;
	rUCON1   = 0x245;
	rUBRDIV1 = ((int)(mclk/16./baud + 0.5) -1);
}

void SerialTxEmpty(void)
{
//	if(SerialPortSel)
		while(!(rUTRSTAT1 & 0x4)); //wait until tx shifter is empty.
//	else
		while(!(rUTRSTAT0 & 0x4)); //wait until tx shifter is empty.

}

void SerialTxChar(char data)
{
	if(SerialPortSel) {
		if(data=='\n') {
			while(!(rUTRSTAT1 & 0x2));
	    	Delay(1);	//because the slow response of hyper_terminal 
			WrUTXH1('\r');
		}
		while(!(rUTRSTAT1 & 0x2)); //Wait until THR is empty.
//		Delay(1);
		WrUTXH1(data);
    } else {
		if(data=='\n') {
			while(!(rUTRSTAT0 & 0x2));
			Delay(1);	//because the slow response of hyper_terminal 
			WrUTXH0('\r');
		}
		while(!(rUTRSTAT0 & 0x2));  //Wait until THR is empty.
//		Delay(1);
		WrUTXH0(data);
    }
}

int SerialRxReady(void)
{
	if(SerialPortSel)
		return (rUTRSTAT1 & 0x1);	//Receive data ready
	else 
		return (rUTRSTAT0 & 0x1);	//Receive data ready
}

char SerialRxKey(void)
{
	if(SerialPortSel) {
		if((rUTRSTAT1 & 0x1)) //Receive data ready
			return RdURXH1();
	} else {
		if((rUTRSTAT0 & 0x1)) //Receive data ready
			return RdURXH0();
	}
	return 0;
}

//*****************************************************************************
int Uart_GetIntNum_GJ(void)
{
    char str[8] ;
    char *string=str;
    int i = 0 ;
    int data = 0 ;
    
    SerialRxToBuf(string);

	while( str[i] != '\0' )
	{
		data = data * 10 ;
		if( str[i]<'0'||str[i]>'9' )
			return -1 ;
		data = data + ( str[i]-'0' ) ;
		i++ ;		
	}	
	
	return data ;
}

char SerialRxChar(void)
{
	if(SerialPortSel) {
		while(!(rUTRSTAT1 & 0x1)); //Receive data ready
		return RdURXH1();
	} else {
		while(!(rUTRSTAT0 & 0x1)); //Receive data ready
		return RdURXH0();
	}
}

int SerialRxToBuf(char *b)
{
	if(SerialPortSel) {
		if(rUTRSTAT1 & 0x1)    //Receive data ready
			*b = RdURXH1();
		else
		    return 0;
    } else {
		if(rUTRSTAT0 & 0x1)    //Receive data ready
		    *b = RdURXH0();
		else
		    return 0;
    }
    
    return 1;
}

void SerialTxString(char *s)
{
	 while(*s)
		SerialTxChar(*s++);
}